import { Entity, Column, OneToMany, JoinColumn, ManyToOne } from "typeorm";

import {
  Book,
  Media,
  Voucher,
  INTEGER_PG,
  VARCHAR50_PG,
  VoucherGroup,
  ENUM_VOUCHER,
  BookMap,
  VARCHAR255_PG,
  VoucherGateway,
  RefVoucherMedia,
  VoucherGroupGateway,
  RefVoucherMediaGateway,
} from "qqlx-core";

import { TransformerInteger } from "@lib/orm.transfor.number";
import { TransformerVarchar50, TransformerVarchar255 } from "@lib/orm.transfor.string";
import { TransformerEnum } from "@lib/orm.transfor.enum";

import { OrderSchema } from "@/alpha/ext.com.order";
import { IdIntroSchema } from "@/alpha/ext.id.intro";
import { OwnerIdSchema } from "@/alpha/ext.id.base";

@Entity({ name: VoucherGroupGateway.relations })
export class VoucherGroupSchema extends IdIntroSchema implements VoucherGroup {
  @OneToMany("VoucherSchema", (s: Voucher) => s.justVoucherGroup)
  joinVoucherList!: Voucher[];
}

@Entity({ name: VoucherGateway.relations })
export class VoucherSchema extends OrderSchema implements Voucher {
  @Column({ transformer: new TransformerEnum(Object.values(ENUM_VOUCHER), ENUM_VOUCHER.NONE) })
  type: ENUM_VOUCHER = ENUM_VOUCHER.NONE;

  @Column({ transformer: new TransformerVarchar255() })
  labelStr: VARCHAR255_PG = "";

  @Column({ transformer: new TransformerInteger() })
  refVoucherGroupId!: INTEGER_PG;

  @ManyToOne("VoucherGroupSchema", (s: VoucherGroup) => s.joinVoucherList)
  @JoinColumn({ name: "refVoucherGroupId", referencedColumnName: "id" })
  justVoucherGroup!: VoucherGroup;

  //

  @OneToMany("RefVoucherMediaSchema", (s: RefVoucherMedia) => s.justVoucher)
  joinRefVoucherMediaList!: RefVoucherMedia[];

  @OneToMany("BookSchema", (s: Book) => s.justVoucher)
  joinBookList!: Book[];

  @OneToMany("BookMapSchema", (s: BookMap) => s.justVoucher)
  joinBookMapList!: BookMap[];
}

@Entity({ name: RefVoucherMediaGateway.relations })
export class RefVoucherMediaSchema extends OwnerIdSchema implements RefVoucherMedia {
  @Column({ transformer: new TransformerVarchar50() })
  refVoucherId!: VARCHAR50_PG;

  @ManyToOne("VoucherSchema", (s: Voucher) => s.joinRefVoucherMediaList)
  @JoinColumn({ name: "refVoucherId", referencedColumnName: "uuid32" })
  justVoucher!: Voucher;

  //

  @Column({ transformer: new TransformerInteger() })
  refMediaId!: Media["id"];

  @ManyToOne("MediaSchema", (s: Media) => s.joinRefVoucherMediaList)
  @JoinColumn({ name: "refMediaId", referencedColumnName: "id" })
  justMedia!: Media;
}
